package com.ruoyi.websocket;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.function.ServerResponse;

import java.io.IOException;

@RestController
public class WebSocketController {

    @RequestMapping("/websocket/{cid}")
    public ModelAndView socket(@PathVariable String cid) {
        ModelAndView mav = new ModelAndView("/websocket/push/" + cid);
        mav.addObject("cid", cid);
        return mav;
    }

    @GetMapping("/websocket/push/{cid}")
    public ServerResponse pushToWeb(@PathVariable String cid, String message) {
        try {
            WebSocketServer.sendInfo(200, message, cid);
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.ok().body(cid + "#" + e.getMessage());
        }
        return ServerResponse.ok().body(cid);
    }
}
